package delayQueue;

import com.rabbitmq.client.*;
import config.RabbitConfig;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author tuyou
 * @date 2020-12-19 21:57:47
 */
public class DelayQueueTest {
    public static void main(String[] args) throws IOException, TimeoutException {

        Connection connection = RabbitConfig.getConnection();
        Channel channel = connection.createChannel();
        Map<String, Object> argss = new HashMap<>();
        argss.put("x-message-ttl" , 10000);
        argss.put("x-dead-letter-exchange", "dlx_exchange");
        channel.queueDelete("delay_queue_produce");
        channel.queueDeclare("delay_queue_produce", false, false, false, argss);
        channel.queueDeclare("delay_queue_consume", false, false, false, null);
        channel.exchangeDeclare("dlx_exchange" , "fanout");
        channel.queueBind("delay_queue_consume", "dlx_exchange", "");

        System.out.println("发送消息延迟");
        channel.basicPublish("", "delay_queue_produce", MessageProperties.TEXT_PLAIN, "123123".getBytes());

        channel.basicConsume("delay_queue_consume", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("receive:" + new String(body));
                channel.basicAck(envelope.getDeliveryTag(), true);
                connection.close();
            }
        });
    }
}
